package com.fangque.kepp.framework.user.service;

import com.fangque.kepp.framework.util.SecurityMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author: Lan
 * @date: 2019/4/9 14:56
 * @description:判断是否具有权限访问当前资源
 */
@Component("judgeAuthorityService")
public class JudgeAuthorityService {

    @Autowired
    private SecurityMeta securityMeta;
    /**
     * 判断是否有权限
     *
     * @param request
     * @param authentication
     * @return
     */
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 排除配置文件中的 例外url
        String[] allowUrl = securityMeta.getAllowUrl();
        for (String url : allowUrl) {
            if (new AntPathRequestMatcher(url).matches(request)) {
                return true;
            }
        }
        // 如果当前用户未登录, 直接返回 token 过期提示
        if ("anonymousUser".equals(authentication.getPrincipal())) {
            return false;
        }
        // 如果当前用户没有权限, 直接返回 token 过期提示
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        if (authorities == null) {
            return false;
        }
        for (GrantedAuthority authority : authorities) {
            if (!StringUtils.isEmpty(authority.getAuthority())) {
                // 匹配所有子目录
                if (new AntPathRequestMatcher(authority.getAuthority()).matches(request)
                        || new AntPathRequestMatcher(authority.getAuthority() + "/**").matches(request)) {
                    return true;
                }
            }
        }
        return false;
    }

}
